<script setup>
	//触底触发异步请求，实现分页查询的下拉选择组件
	import { ref, getCurrentInstance, watch } from 'vue';
	const { proxy } = getCurrentInstance();
	const emit = defineEmits(['selectChange', 'treeSelectData']);
	const props = defineProps({
		//placeholder提示
		placeholder: {
			type: String,
			default: '',
		},
		//是否可多选
		multiple: {
			type: Boolean,
			default: false
		},
		//是否允许清空
		allowClear: {
			type: Boolean,
			default: true
		},
		//是否禁用
		disabled: {
			type: Boolean,
			default: false
		},
		//为空提示
		placeholder: {
			type: String,
			default: '请选择'
		},
		//禁用连级复选
		checkStrictly: {
			type: Boolean,
			default: true
		},
		//超过自定便签后折叠
		minCollapsedNum: {
			type: Number,
			default: 3
		},
		//是否开启搜索
		search: {
			type: Boolean,
			default: true
		},
		//是否开启懒加载
		lazy: {
			type: Boolean,
			default: false
		},
		//替换 data 中id title children 字段名
		replaceFields: {
			type: Object,
			default: () => {
				return { id: "id", title: "name", children: "children" }
			}
		},
		//是否默认打开所有节点
		defaultExpandAll: {
			type: Boolean,
			default: true
		},
		//数据url
		url: {},
		//本地数据
		localData: {
			type: Array,
			default: () => {
				return []
			}
		},
		//显示子字段
		labelName2: {
			type: String,
			default: ''
		},
		selectVal: {
			type: [String, Number],
			default: ''
		},
		//搜索条件
		params: {
			type: Object,
			default: () => {
				return {}
			}
		},
		// 禁用key集合
		disabledList: {
			type: Array,
			default: () => {
				return []
			}
		}
	});

	const data = ref([]);
	const selectValue = ref(JSON.parse(JSON.stringify(props.selectVal)))
	if (props.url) {
		getData()
	} else {
		data.value = props.localData
	}

	function getData() {
		props.url(props.params).then(res => {
			let list = res.data || []
			if (props.labelName2) {
				list.forEach(item => {
					if(props.disabledList.includes(item[props.replaceFields.id])) item.disabled = true
					item[props.replaceFields.title] = `${item[props.replaceFields.title]} - ${item[props.labelName2]}`
				})
			}
			data.value = proxy.$common.setTreeData(list)
			emit('treeSelectData', list);
		})
	}

	//懒加载回调
	const handleLoad = (node, resolve) => {

	};

	//监听选中值变化事件	
	function handleChange(e) {

	}

	//监听选中值变化
	watch(() => selectValue.value, (newVal) => {
		emit('selectChange', selectValue.value);
	})
	
	//监听本地数据的变化
	watch(() => props.localData, (newVal) => {
		data.value = props.localData
	})
</script>
<template>
	<lay-tree-select @change="handleChange" v-model="selectValue" :data="data" :lazy="lazy" :load="handleLoad" :multiple="multiple" :default-expand-all="defaultExpandAll" :replace-fields="replaceFields" :allow-clear="allowClear" :search="search"
		:min-collapsed-num="minCollapsedNum" :check-strictly="checkStrictly" :disabled="disabled" :placeholder="placeholder" style="width: 100%;">
	</lay-tree-select>
</template>

<style lang="scss" scoped></style>